package com.vincent.tvui;

import com.vincent.tvui.exception.NoSuchViewException;

import android.content.Context;

import java.lang.reflect.Constructor;
import java.util.Map;

/**
 * 项目：TvLauncher 作者：907357 时间：2016/10/13 16:33 版本：1.0 描述：描述内容
 */

public class CellViewFactory implements CellLayoutInflater.Factory {

    private static final String prefix = "com.vincent.tvui.";
    private CellViewController mCellViewController;
    private static CellViewFactory sCellViewFactory;

    protected CellViewFactory() {
    }

    public static CellViewFactory getInstance() {
        if (sCellViewFactory == null) {
            sCellViewFactory = new CellViewFactory();
        }

        return sCellViewFactory;
    }

    @Override
    public CellView onCreateView(String prefix, String name, Context context, Map<String, String> styles) {
        if (name == null || name.equals("")) {
            throw new RuntimeException("name is null");
        }

        CellView cellView = null;
        StringBuffer stringBuffer;
        if (prefix == null || prefix.equals("")) {
            stringBuffer = new StringBuffer(CellViewFactory.prefix);
        } else {
            stringBuffer = new StringBuffer(prefix);
        }
        stringBuffer.append(name);

        try {
            Class<?> clazz = Class.forName(stringBuffer.toString());

            Constructor constructor = clazz.getConstructor(Context.class);
            Object view = constructor.newInstance(context);
            if (view instanceof CellView) {
                cellView = (CellView) view;
                cellView.setController(mCellViewController);
                cellView.setStyles(styles);
            }

            return cellView;
        } catch (Exception e) {
            throw new NoSuchViewException(e);
        }
    }

    @Override
    public void setCellViewController(CellViewController controller) {
        this.mCellViewController = controller;
    }
}
